//
//  CZDetailHeaderView.swift
//  GZWeibo666
//
//  Created by ksl on 15/12/2.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

//MARK:按钮点击代理
///按钮点击代理
protocol CZDetailHeaderViewDelegate: NSObjectProtocol {
    /**
    headerView被点击了
    - parameter view:   headerView
    */
    func detailHeaderViewClick(headerView: UIView)
}



class CZDetailHeaderView: UIView {

    //MARK: 属性
    ///代理
    weak var delegate: CZDetailHeaderViewDelegate?
    
    ///微博模型
    var status: CZStatus? {
        didSet {
            setButton(CommentButton, title: "评论", count: status!.comments_count)
        }
    }
    
    //MARK: 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置背景颜色
        backgroundColor = UIColor(white: 0.99, alpha: 1)
        
        prepareUI()
    }
    //MARK: - 设置按钮文字
    
    private func setButton(button: UIButton, title: String, count: Int) {
        if count >= 10000 {
            
            let final = CGFloat(count) / 10000.0
            
            var titleText = String(format: "%.1f万", arguments: [final])
            
            titleText = titleText.stringByReplacingOccurrencesOfString(".0", withString: "")
            
            button.setTitle(title + " " + titleText, forState: UIControlState.Normal)
        } else {
            button.setTitle("\(title) \(count)", forState: UIControlState.Normal)
        }
    }

    
    //MARK: 按钮点击事件
    
    func buttonClick(button: UIButton) {
        
        //通知代理
        delegate?.detailHeaderViewClick(button)
    }
    
    
    //MARK: 准备 UI
    private func prepareUI() {
        // 添加子控件
        self.addSubview(CommentButton)
        
        ///增加点击事件
        CommentButton.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 添加约束
        CommentButton.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraint(NSLayoutConstraint(item: CommentButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 20))
        self.addConstraint(NSLayoutConstraint(item: CommentButton, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    // 懒加载
    private lazy var CommentButton: UIButton = {
        let button = UIButton()
        
        button.setTitle("评论", forState: UIControlState.Normal)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(11)
        
        button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
        
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
      
        button.sizeToFit()
        return button
    }()
}
